<?php
/**
 * Created by PhpStorm.
 * User: dell
 * Date: 2017/6/14
 * Time: 14:27
 */

namespace Weixin\Service;


use Common\Common\Service;
use Weixin\Component\Weixin\WeixinComponent;
use Weixin\Exception\WeixinException;
use Weixin\Request\Weixin\AddWeixinRequest;
use Weixin\Response\AddWeixinResponse;

class AddWeixinService implements Service
{
    public function run(AddWeixinRequest $request = null)
    {
        if ($request->issetOpenid() == false) {
            throw new WeixinException(10001);
        }
        if ($request->issetSubscribe() == false) {
            throw new WeixinException(10001);
        }
        if ($request->verifySubscribe() == false) {
            throw new WeixinException(10002);
        }

        $openid = $request->getOpenid();
        $subscribe = $request->getSubscribe();
        $data['openid'] = $openid;
        $data['subscribe'] = $subscribe;

        $response = new AddWeixinResponse();
        $component = new WeixinComponent();
        try {
            $data = $component->addWeixin($data);
            if (!$data) {
                $response->setItIsNull();
            } else {
                $response->setWeixinId($data);
            }
        } catch (WeixinException $e) {
            throw new WeixinException($e->getMessage(), $e->getCode());
        }
        return $response;
    }
}